# 任务：预测房价

# 以面积为输入变量，建立单因子模型进行预测
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

data = pd.read_csv('usa_housing_price.csv')
# Avg. Area Income,Avg. Area House Age,Avg. Area Number of Rooms,Area Population,size,Price
income = data.loc[:, 'Avg. Area Income']
house_age = data.loc[:, 'Avg. Area House Age']
rooms = data.loc[:, 'Avg. Area Number of Rooms']
population = data.loc[:, 'Area Population']
size = data.loc[:, 'size']
price = data.loc[:, 'Price']
# print(income, house_age, rooms, population, size, price)

# 画图展示

# 设置字体 显示汉字
plt.rcParams["font.sans-serif"] = "SimHei"
# 取消使用 unicode 的负号
plt.rcParams["axes.unicode_minus"] = False

fig = plt.figure(figsize=(10, 10))
plt.title('单因子 vs Price')

fig1 = plt.subplot(231)
plt.scatter(income, price)
plt.title('Avg. Area Income vs Price')
plt.xlabel('Avg. Area Income')
plt.ylabel('Price')

fig2 = plt.subplot(232)
plt.scatter(house_age, price)
plt.title('Avg. Area House Age vs Price')
plt.xlabel('Avg. Area House Age')
plt.ylabel('Price')

fig3 = plt.subplot(233)
plt.scatter(rooms, price)
plt.title('Avg. Area Number of Rooms vs Price')
plt.xlabel('Avg. Area Number of Rooms')
plt.ylabel('Price')

fig4 = plt.subplot(234)
plt.scatter(population, price)
plt.title('Area Population vs Price')
plt.xlabel('Area Population')
plt.ylabel('Price')

fig5 = plt.subplot(235)
plt.scatter(size, price)
plt.title('size vs Price')
plt.xlabel('size')
plt.ylabel('Price')

# plt.show()
# 下载图片
# plt.savefig('single_factor_vs_price.png')、

# 以面积作为输入变量进行训练
x = np.array(size).reshape(-1, 1)
y = np.array(price).reshape(-1, 1)
lr1_model = LinearRegression()
lr1_model.fit(x, y)
# 评估模型
y_predict = lr1_model.predict(x)
print('均方差:', mean_squared_error(y, y_predict))
print('R2分数:', r2_score(y, y_predict))

# 可视化展示
fig6 = plt.subplot(236)
plt.title('面积预测价格',)
plt.scatter(x, y)
plt.plot(x, y_predict, 'r')  # 红色
# plt.show()
plt.savefig('single_factor_vs_price.png')
